import {
  Card,
  Row,
  Col,
  List,
  Badge,
  Breadcrumb,
  Button,
  message,
  Popover,
  Popconfirm,
  Modal,
  Input,
  notification,
} from 'antd';
import { CloseCircleOutlined, SmileOutlined } from '@ant-design/icons';
import * as echarts from 'echarts';
import { useEffect, useState } from 'react';
import { ArticleModelState, Link, useDispatch, useSelector } from 'umi';
import Footer from '@/components/commonFooter';
import style from './index.less';
import './default.less';
const { TextArea } = Input;
const list = [
  {
    path: '/article',
    title: '文章管理',
  },
  {
    path: '/comment',
    title: '评论管理',
  },
  {
    path: '/file',
    title: '文件管理',
  },
  {
    path: '/user',
    title: '用户管理',
  },
  {
    path: '/view',
    title: '访问统计',
  },
  {
    path: '/setting',
    title: '系统设置',
  },
];

export default function IndexPage() {
  //获取个人信息
  const user = JSON.parse(localStorage.getItem('user')!);
  const dispatch = useDispatch();
  const { articleList, commentList } = useSelector(
    (state: { workbench: ArticleModelState }) => state.workbench,
  );

  useEffect(() => {
    // 请求页面数据
    dispatch({
      type: 'workbench/getArticleList',
    });
    // 评论数据
    dispatch({
      type: 'workbench/getCommentList',
    });
  }, []);
  // echarts
  useEffect(() => {
    let chartDom = document.getElementById('main');
    let myChart = echarts.init(chartDom!);
    let option;
    option = {
      title: {
        text: '每周用户访问指标',
        left: '20',
        top: '20',
      },
      legend: {
        data: ['评论数', '访问量'],
      },
      xAxis: [
        {
          type: 'category',
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
          axisPointer: {
            type: 'shadow',
          },
        },
      ],
      yAxis: [
        {
          type: 'value',
          min: 0,
          max: 400,
          interval: 100,
          axisLine: {
            show: true,
            lineStyle: {
              color: '#000',
            },
          },
          axisLabel: {
            formatter: '{value}',
          },
        },
        {
          type: 'value',
          min: 0,
          interval: 100,
          axisLabel: {
            formatter: '',
          },
        },
      ],
      series: [
        {
          name: '评论数',
          type: 'bar',
          color: '#b00',
          data: [120, 200, 150, 70, 65, 110, 135],
        },
        {
          name: '访问量',
          type: 'line',
          color: '#000',
          yAxisIndex: 1,
          data: [370, 300, 350, 110, 100, 115, 180],
        },
      ],
    };
    option && myChart.setOption(option);
  }, []);
  function confirm() {
    message.info('Clicked on Yes.');
  }
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [inputText, setInputText] = useState('');
  const [data, setData] = useState({ content: '' });
  // 回复弹窗
  const showModal = (data: any) => {
    setData(data);
    setIsModalVisible(true);
  };
  // 回复事件
  const handleOk = () => {
    if (user.email) {
      setIsModalVisible(false);
      let tempdata = Object.assign({}, data);
      tempdata.content = inputText;
      dispatch({
        type: 'workbench/getCommentReply',
        payload: tempdata,
      });
      message.success('回复成功');
    } else {
      notification.open({
        message: '回复评论失败',
        description: '请前往系统设置完善 SMTP 设置，前往个人中心更新个人邮箱。',
        icon: <CloseCircleOutlined style={{ color: '#f00' }} />,
      });
      setIsModalVisible(false);
    }
  };
  const handleCancel = () => {
    setIsModalVisible(false);
  };

  // 通过评论
  async function adopt(id: string) {
    if (user.status !== 'active') {
      message.warning('访客无权进行该操作');
    } else {
      await dispatch({
        type: 'workbench/getCommentAdopts',
        payload: {
          id,
          obj: { pass: true },
        },
      });
      await dispatch({
        type: 'workbench/getCommentList',
      });
      message.success('评论已通过');
    }
  }
  // 拒绝评论
  async function notAdopt(id: string) {
    if (user.status !== 'active') {
      message.warning('访客无权进行该操作');
    } else {
      await dispatch({
        type: 'workbench/getCommentAdopts',
        payload: {
          id,
          obj: { pass: false },
        },
      });
      await dispatch({
        type: 'workbench/getCommentList',
      });
      message.success('评论已拒绝');
    }
  }
  // 删除评论
  async function deleteComment(data: any) {
    await dispatch({
      type: 'workbench/getCommentDelete',
      payload: {
        id: data.id,
        data,
      },
    });
    await dispatch({
      type: 'workbench/getCommentList',
    });
    message.success('评论已删除');
  }
  return (
    <>
      <div className={style.workbench_header}>
        <Breadcrumb>
          <Breadcrumb.Item>
            <Link to="/">工作台</Link>
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className={style.workbench_empty}></div>
        <div className={style.workbench_user_infor}>
          <h1>您好，{JSON.parse(localStorage.getItem('user')!).name}</h1>
          <p>
            您的角色：
            {JSON.parse(localStorage.getItem('user')!).status == 'active'
              ? '管理员'
              : '来访者'}
          </p>
        </div>
      </div>
      <div className="workbench_main">
        <Card title="面板导航" bordered={false}>
          <div id="main" style={{ height: '300px' }}></div>
        </Card>
        <Card title="快速导航" bordered={false} style={{ marginTop: '24px' }}>
          <Row>
            {list.map((item, index) => {
              return (
                <Col key={index} span={4}>
                  <Link to={item.path}>{item.title}</Link>
                </Col>
              );
            })}
          </Row>
        </Card>
        <Card
          size="small"
          title="最新文章"
          extra={<Link to="/article">全部文章</Link>}
          style={{ marginTop: '24px' }}
        >
          {articleList.length
            ? articleList.map((item, index) => {
                return (
                  <Card.Grid
                    key={index}
                    style={{ width: '33.3%', textAlign: 'center' }}
                  >
                    <Link
                      to={`/article/editor/${item.id}`}
                      className={style.images}
                    >
                      <img src={item.cover} alt="文章封面" />
                      <p>{item.title}</p>
                    </Link>
                  </Card.Grid>
                );
              })
            : ''}
        </Card>
        <Card
          size="small"
          title="最新评论"
          extra={<Link to="/comment">全部评论</Link>}
          style={{ marginTop: '24px' }}
        >
          <List
            size="large"
            dataSource={commentList}
            /* renderItem={(item) => <List.Item>{item.content}</List.Item>} */
            renderItem={(item) => (
              <List.Item
                className={style.workbench_comment}
                actions={[
                  <button
                    onClick={() => {
                      adopt(item.id);
                    }}
                  >
                    通过
                  </button>,
                  <button
                    onClick={() => {
                      notAdopt(item.id);
                    }}
                  >
                    拒绝
                  </button>,

                  <button
                    onClick={() => {
                      showModal(item);
                    }}
                  >
                    回复
                  </button>,
                  <Popconfirm
                    title="确认删除这条评论?"
                    okText="确认"
                    cancelText="取消"
                    onConfirm={() => {
                      deleteComment(item);
                    }}
                  >
                    <button>删除</button>
                  </Popconfirm>,
                ]}
              >
                <List.Item.Meta
                  title={
                    <div>
                      <span>{item.name}</span> 在
                      <Popover
                        placement="right"
                        content={
                          <div className="markdown">
                            {
                              <iframe src="https://creationadmin.shbwyz.com/login"></iframe>
                            }
                          </div>
                        }
                        title="页面预览"
                      >
                        <Button type="link">文章</Button>
                      </Popover>
                      <span>评论</span>
                      <Popover
                        content={<div className="markdown">{item.content}</div>}
                        title="评论详情-原始内容"
                      >
                        <Button type="link">查看内容</Button>
                      </Popover>
                      {item.pass ? (
                        <Badge status="success" text="通过" />
                      ) : (
                        <Badge status="warning" text="未通过" />
                      )}
                    </div>
                  }
                />
              </List.Item>
            )}
          />
          <Modal
            title="回复评论"
            visible={isModalVisible}
            onOk={handleOk}
            onCancel={handleCancel}
            okText="回复"
            cancelText="取消"
          >
            <TextArea
              rows={4}
              placeholder="支持 Markdown"
              maxLength={10}
              style={{ height: '142px' }}
              value={inputText}
              onChange={(e) => {
                setInputText(e.target.value);
              }}
            />
          </Modal>
        </Card>
        <Footer />
      </div>
    </>
  );
}
